const { DefinePlugin } = require('webpack');
const resolveApp = require('./paths');
const VueLoaderPlugin = require('vue-loader/lib/plugin'); // 配合 vue-loader 使用，用于编译转换 
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 生成 index.html
const { merge } = require('webpack-merge'); // 合并配置
const prodConfig = require('./webpack.prod');
const devConfig = require('./webpack.dev');

const commonConfig = {
  entry: './src/index.js',
  resolve: {
    extensions: ['.js', '.json', '.vue'],
    alias: {
      '@': resolveApp('./src')
    }
  },
  output: {
    filename: 'js/[name].build.js',
    path: resolveApp('./dist'),
    assetModuleFilename: 'img/[name].[hash:6].[ext]'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: ['vue-loader'] //顺序是从右到左
      },
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'] // 插件集合
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader', 'css-loader']
      },
      {
        test: /\.less$/,
        use: ['style-loader' ,'css-loader' ,'less-loader']
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        type: 'asset/resource'
      },
      {
        test: /\.(js|vue)$/, // 配置 eslint-loader 检查代码规范
        use: {
          loader: 'eslint-loader',
          options: {
            formatter: require('eslint-friendly-formatter') // 默认的错误提示方式
          }
        },
        enforce: 'pre', // 编译前检查
        exclude: /node_modules/, // 不检查的文件
        include: [__dirname + '/src'], // 要检查的目录
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'copyWebpackPlugin',
      template: './public/index.html'
    }),
    new VueLoaderPlugin(),
    new DefinePlugin({
      BASE_URL: '"./"'
    })
  ]
}

module.exports = (env) => {
  const config = env.production ? prodConfig : devConfig;
  const mergeConfig = merge(commonConfig, config);
  console.log(mergeConfig)
  return mergeConfig;
}